package com.ywwxhz.plugins.pkgmgr.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;

import com.ywwxhz.Util.PreferencesKit;
import com.ywwxhz.model.AppInfo;

import java.io.File;
import java.io.FilenameFilter;
import java.util.HashMap;

public class FileUtil {

    private static final FilenameFilter APK_FILTER = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String filename) {
            return filename.endsWith(".apk");
        }
    };

    public static File getBackUpDir(Context context) throws Exception {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File path = new File(Environment.getExternalStorageDirectory()
                    .getAbsolutePath()
                    + "/"
                    + PreferencesKit.getString(context, "path", "App"));
            if (!path.exists()) {
                path.mkdirs();
            }
            return path;
        }
        throw new Exception("can't read external storage");
    }

    public static long getFolderSize(Context context) throws Exception {
        long size = 0;
        File[] fileList = getBackUpDir(context).listFiles(APK_FILTER);
        for (File file : fileList) {
            size += file.length();
        }
        return size;
    }

    public static HashMap<String, AppInfo> getBackupAppMap(Context context)
            throws Exception {
        HashMap<String, AppInfo> apps = new HashMap<String, AppInfo>();
        File[] fileList = getBackUpDir(context).listFiles(APK_FILTER);
        for (File file : fileList) {
            AppInfo info = apkInfo(file.getAbsolutePath(), context);
            if (info != null) {
                apps.put(info.getPkgName(), info);
            }
        }

        return apps;
    }

    public static void cleanAPK(Context context) throws Exception {
        File[] fileList = getBackUpDir(context).listFiles(APK_FILTER);
        for (File file : fileList) {
            file.delete();
        }
    }

    private static AppInfo apkInfo(String absPath, Context context) {
        AppInfo info = null;
        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(absPath,
                PackageManager.GET_ACTIVITIES);
        if (pkgInfo != null) {
            info = new AppInfo();
            ApplicationInfo appInfo = pkgInfo.applicationInfo;
            /* 必须加这两句，不然下面icon获取是default icon而不是应用包的icon */
            appInfo.sourceDir = absPath;
            appInfo.publicSourceDir = absPath;
            info.setAppLabel(pm.getApplicationLabel(appInfo).toString());
            info.setPkgName(appInfo.packageName);
            info.setVersionCode(pkgInfo.versionCode);
            info.setVersion(pkgInfo.versionName);
            info.setAppIcon(pm.getApplicationIcon(appInfo));
            info.setSourceDir(absPath);
        }
        return info;
    }

    public static boolean isExist(Context context, String pkgName,
                                  int versionCode) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            try {
                File file = new File(getBackUpDir(context).getAbsolutePath() + "/"
                        + pkgName + "_" + versionCode + ".apk");
                return file.exists();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }
}
